package com.css.apps.base.org.action;

import com.css.apps.base.org.model.SOrg;
import com.css.core.model.tree.Tree;
import com.css.core.model.tree.TreeCache;
import com.css.core.model.tree.TreeNode;
import com.css.db.page.Page;
import com.css.db.query.QueryCache;
import com.css.util.ListUtil;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("serial")
public class DirOrg extends AdminAction {
	
	private static Log log = LogFactory.getLog(DirOrg.class);
	private String name, parentId, orgLevel;
	private String includeFlag = "1";
	private String openFlag;
	private String postIdsea;
	private Page page;
	private List<String> nodeList;
	private String isBranch ="N";

	public DirOrg() {
		page = new Page();
		page.setCurrentPage(1);
		page.setPageSize(15);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected String adminGo() {
		try {
			nodeList = new ArrayList<String>();
			Tree tree = new TreeCache(SOrg.class);
			String nodeId = parentId;
			if (StringHelper.isEmpty(parentId)) {
				nodeId = "Y".equalsIgnoreCase(isBranch) ? tree.getTreeNode(sUser.getOrganId()).getNodeId() : tree.getRoot().get(0).getNodeId();
			}
			nodeList.add(nodeId);

			if ("2".equals(includeFlag) && tree != null) {
				for (TreeNode node : tree.getTree()) {
					nodeList.add(node.getNodeId());
				}
			}
			QueryCache qc = new QueryCache("select a.uuid from SOrg a " + getWhere() + getOrder());
			setWhere(qc);
			List<SOrg> orgItems = QueryCache.idToObj(SOrg.class, qc.list());
			List<SOrg> newOrgItems = new ArrayList<>();
			for (SOrg item : orgItems) {
				newOrgItems.add(item);
			}
			if (StringHelper.isNotEmpty(postIdsea) && orgItems != null) {
				for (SOrg item : orgItems) {
					if (!item.getPostList().getListById().contains(postIdsea)) {
						newOrgItems.remove(item);
					}
				}
			}
			page.setResults(newOrgItems);
			loadPage(page);
			return SUCCESS;
		} catch (Exception ex) {
			setMessage(Messages.getString("systemMsg.exception"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		}
	}

	public String getWhere() {
		Tree tree = new TreeCache(SOrg.class);
		StringBuffer sb = new StringBuffer("where a.delFlag = '2' ");
		if (StringHelper.isNotEmpty(name))
			sb.append(" and a.name like :name ");
		if (StringHelper.isNotEmpty(openFlag))
			sb.append(" and a.openFlag = :openFlag ");
		if (nodeList != null && nodeList.size() > 0) {
			TreeNode rootNode = tree.getRoot().get(0);
			if (nodeList.size() > 2000) {
				if (StringHelper.isEmpty(parentId) || (StringHelper.isNotEmpty(parentId) && (tree.getTreeNode(parentId) == rootNode)))
					sb.append("  and (a.parentId in( " + StringHelper.listToStr(nodeList) + ") or a.parentId is null ) ");
				else {
					sb.append("  and (a.parentId in( " + StringHelper.listToStr(nodeList) + ") ) ");
				}
			} else {
				if (StringHelper.isEmpty(parentId) || (StringHelper.isNotEmpty(parentId) && (tree.getTreeNode(parentId) == rootNode)))
					sb.append(" and (a.parentId in(:nodeList) or a.parentId is null) ");
				else {
					sb.append(" and (a.parentId in(:nodeList) ) ");
				}
			}
		}
		return sb.toString();
	}

	public String getOrder() {
		return StringHelper.isNotEmpty(page.getOrderByString()) ? page.getOrderByString() : "order by a. orderNum, a.openFlag";
	}

	public void setWhere(QueryCache qc) {
		if (StringHelper.isNotEmpty(name))
			qc.setParameter("name", "%" + name.trim() + "%");
		if (StringHelper.isNotEmpty(openFlag))
			qc.setParameter("openFlag", openFlag);
		if (ListUtil.isLstNotEmpty(nodeList) && nodeList.size() < 2000) {
			qc.setParameter("nodeList", nodeList);
		}
	}

	private void loadPage(Page page) {
		List<?> results = page.getResults();
		if (results != null && results.size() > 0) {
			page.setTotalRows(results.size());
			page.setTotalPages((int) Math.ceil(results.size() * 1.0 / page.getPageSize()));
			int total = results.size();
			int curPage = page.getCurrentPage();
			int pageSize = page.getPageSize();
			if (curPage > page.getTotalPages()) {
				curPage = page.getTotalPages();
			}
			int startIndex = (curPage > 0 ? curPage - 1 : 0) * pageSize;
			if (startIndex > total) {
				startIndex = 0;
			}
			int endIndex = startIndex + pageSize;
			if (endIndex > total) {
				endIndex = total;
			}
			results = results.subList(startIndex, endIndex);
			page.setResults(results);
		}
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public String getOpenFlag() {
		return openFlag;
	}

	public void setOpenFlag(String openFlag) {
		this.openFlag = openFlag;
	}

	public String getIncludeFlag() {
		return includeFlag;
	}

	public void setIncludeFlag(String includeFlag) {
		this.includeFlag = includeFlag;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPostIdsea() {
		return postIdsea;
	}

	public void setPostIdsea(String postIdsea) {
		this.postIdsea = postIdsea;
	}

	public String getOrgLevel() {
		return orgLevel;
	}

	public void setOrgLevel(String orgLevel) {
		this.orgLevel = orgLevel;
	}

	public List<String> getNodeList() {
		return nodeList;
	}

	public void setNodeList(List<String> nodeList) {
		this.nodeList = nodeList;
	}

	public String getIsBranch() {
		return isBranch;
	}

	public void setIsBranch(String isBranch) {
		this.isBranch = isBranch;
	}
}
